package org.dromara.system.pay;

import cn.hutool.http.HttpUtil;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

/**
 * 证书模式公众号支付
 */
@Slf4j
@Service
public class WxPayJsapiCertEndService {

    /**
     * 微信支付配置文件
     */
    private static PayConfigUtils config = new PayConfigUtils();

    /**
     * 退款url
     */
    public static final String REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
    /**
     * 付款url
     */
    public static final String WITHDRAW_URL = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";


    /**
     * 公众号微信证书模式支付
     *
     * @param map     参数
     * @param request 请求
     * @return
     * @throws Exception
     */
    public static Map<String, String> createAppPayment(Map<String, String> map, HttpServletRequest request) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appid", AppletConstants.waterAppId);
        params.put("mch_id", config.mch_id);
        params.put("nonce_str", WXPayUtil.generateNonceStr());
        params.put("body", "会员充值");
        params.put("out_trade_no", map.get("tradeNo"));
        BigDecimal total = new BigDecimal(map.get("amount")).multiply(new BigDecimal(100));
        DecimalFormat df = new DecimalFormat("0");
//        params.put("total_fee", df.format(total));
        params.put("total_fee", "1");
        params.put("spbill_create_ip", request.getRemoteAddr());
        params.put("notify_url", map.get("notifyUrl"));
        params.put("trade_type", "JSAPI");
        params.put("openid", map.get("openId"));
        String sign = WXPayUtil.generateSignature(params, config.api_key, WXPayConstants.SignType.MD5);
        params.put("sign", sign);
        log.info("-------------------------公众号支付参数----------------------:" + params);
        // 发送请求并解析响应
        String xmlParam = WXPayUtil.mapToXml(params);
        log.info("最终发送给微信的 XML: \n" + xmlParam);
        String response = HttpUtil.post("https://api.mch.weixin.qq.com/pay/unifiedorder", xmlParam);
        Map<String, String> responseMap = WXPayUtil.xmlToMap(response);
        log.info("公众号支付返回结果: \n" + responseMap);
        return getJsApiParams(responseMap.get("prepay_id"));
    }

    public static Map<String, String> getJsApiParams(String prepayId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("appId", AppletConstants.waterAppId);
        params.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
        params.put("nonceStr", WXPayUtil.generateNonceStr());
        params.put("package", "prepay_id=" + prepayId);
        params.put("signType", "MD5");
        // 二次签名
        String paySign = WXPayUtil.generateSignature(params, config.api_key, WXPayConstants.SignType.MD5);
        params.put("paySign", paySign);
        return params;
    }
}

